<template>
  <!-- 危险源清单项添加 -->
  <div>
    <a-modal
    title="危险源清单项"
    cancelText="取消"
    okText="保存"
    :visible="visible"
    :width="900"
    @cancel="cancel"
    @ok="handleOk"
    :confirmLoading="loading"
  >
  <a-spin :spinning="loading">
    <div class="about-master-container">
      <BForm
        ref="BForm"
        :config="formConfig"
        :form="form"
        :rule="rules"
      />
      <div class="bim-btn">
        <div class="label">BIM模型：</div>
        <div class="data-val" v-if="bimListData.length"><span v-for="(item,index) in bimListData" :key="item.name"><img src="~@/assets/unit.png"/>{{item.name}}<a-icon @click="delBim(index)" type="close" /></span></div>
        <a-button type="primary" @click="relevanceBim(true)" style="margin-left:30px" :loading='loadingBtn'>关联模型</a-button>
      </div>
    </div>
  </a-spin>
  </a-modal>
     <!-- BIM模型列表弹窗 -->
  <BimView
      ref="bimView"
      :visible.sync="visibleBim"
      :zIndex="1001"
      :extraParams="extraParams"
      @handleOpen="handleOpen"
    />
    <!-- 关联BIM模型弹窗 -->
    <BimRelease
      ref="bimRelease"
      :zIndex="1002"
      :destroyOnClose="true"
      :isRelease="false"
      :visible.sync="visibleRelease"
      :modelList="modelList"
      :isConstructData="true"
      :highLightList="highLightList"
      @confirmSelect="handleBim"
    />
  </div>
</template>

<script>
import SelectPersonByProject from '@/components/Select/SelectPersonByProject.vue'
import OrgStaffAsync from '@/components/TreeSelectOrganization/orgStaffAsync.vue'
import BSelect from '@/components/BComponents/BSelect'
import Api from '@/api/office/hazardIdentification'
import BimRelease from '@/components/Dialog/BimRelease' // BIM模型关联
import { getList } from '@/api/bimIntegrate/bimModel'
import BimView from '@/components/Dialog/BimView' // BIM模型关联列表

export default {
  name: 'a' + Date.now(),
  components: {
    OrgStaffAsync,
    SelectPersonByProject,
    BimRelease,
    BimView
  },
  props: {
    initData: {
      type: Object,
      default() {
        return {}
      }
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    formConfig() {
      return [
        {
          row: true,
          children: [
            {
              type: 'custom', value: 'areaId', label: '区域', colSpan: 12,
              render: () => {
                return (
                  <a-tree-select
                    dropdownStyle={{ maxHeight: '400px', overflow: 'auto' }}
                    v-model={this.form.areaId}
                    show-search
                    replaceFields={{ children: 'children', title: 'name', key: 'id', value: 'id' }}
                    placeholder="请选择"
                    tree-data={this.treeData}
                    onSelect={this.onSelectTree}
                    allow-clear
                  />
                )
              }
            },
            {
              type: BSelect, value: 'itemTypeId', label: '分部分项工程', colSpan: 12,
              attrs: {
                disabled: this.disabled,
                request: () => Api.typesLabel({}, { type: 17 })
              }
            },
            {
              type: 'range-picker', value: 'planTime', label: '预计实施时间', colSpan: 12,
              attrs: {
                valueFormat: 'YYYY-MM-DD',
                format: 'YYYY-MM-DD',
                disabled: this.disabled
              }
            },
            { type: 'input', value: 'parameter', label: '危险参数', colSpan: 12, attrs: { disabled: this.disabled } },
            {
              type: 'textarea',
              value: 'dangerSource',
              label: '危险源',
              colSpan: 24,
              noFixed: true,
              attrs: { disabled: this.disabled, max: 300 }
            },
            {
              type: BSelect, value: 'levelTypeId', label: '风险等级', colSpan: 12,
              attrs: {
                disabled: this.disabled,
                request: () => Api.typesLabel({}, { type: 28 })
              }
            },
            {
              type: BSelect, value: 'dangerousTypeId', label: '危大工程等级', colSpan: 12,
              attrs: {
                disabled: this.disabled,
                request: () => Api.typesLabel({}, { type: 29 })
              }
            },
            {
              type: SelectPersonByProject, value: 'dutyUserTemp', label: '责任人', colSpan: 12, noFixed: true,
              attrs: {
                mode: 'multiple',
                showSearch: true,
                 noRepeat:true,
                 labelInValue: true,
                'option-label-prop': 'children',
                projectId: this.form.projectId
              }
            },
            {
              type: 'textarea',
              value: 'controlContent',
              label: '控制措施',
              colSpan: 24,
              noFixed: true,
              attrs: { disabled: this.disabled, max: 300 }
            }
          ]
        }
      ]
    },
    // 查看关联BIM模型列表请求参数
    extraParams() {
      return { projectId: this.form.projectId  }
    }
  },
  data() {
    return {
      loading: false,
      disabled: false,
      loadingBtn:false,
      form: { areaId: undefined, projectId: undefined, dutyUserTemp: [], planTime: [] },
      selectList: [],
      // treeData: [],
      treeData: [],
      rules: {
        areaId: [{ required: true, message: '请选择区域', trigger: 'change' }],
        itemTypeId: [{ required: true, message: '请选择分部分项工程', trigger: 'change' }],
        planTime: [{ required: true, message: '请选择预计实施时间', trigger: 'change' }],
        parameter: [{ required: true, message: '请输入危险参数', trigger: 'blur' }],
        dangerSource: [{ required: true, message: '请输入危险源', trigger: 'blur' }],
        levelTypeId: [{ required: true, message: '请选择风险等级', trigger: 'change' }],
        dangerousTypeId: [{ required: true, message: '请选择危大工程等级', trigger: 'change' }],
        dutyUserTemp: [{ required: true, message: '请选择责任人', trigger: 'change' }],
        controlContent: [{ required: true, message: '请输入控制措施', trigger: 'change' }]
      },
      visibleBim: false, // BIM模型列表弹窗控件
      visibleRelease: false, // BIM模型关联弹窗控件
      modelList: [], // BIM模型列表
      // 查看关联BIM模型列表请求参数
      bimListData:[],
      highLightList:'',
      firstBimData:{}, //取列表第一个数据
    }
  },
  created() {
  },
  watch: {
    visible(v) {
      if (v) {
        console.log(12222222)
        this.$nextTick(() => {
          this.getData()
          this.form = Object.assign(this.form, this.initData)
          if (this.form.id) {
            this.form.dutyUserTemp = []
            this.form.planTime = [this.form.planTime, this.form.planTimeEnd]
            this.relevanceBim()
            Object.keys(this.form.dutyUser).map(key => {
              this.form.dutyUserTemp.push({ key, label: this.form.dutyUser[key] })
            })
            let arr = this.form.bimId?.split('&&&&') || [];
            if(arr.length){
              this.highLightList = arr[1];
              let obj = {
                name:arr[0],
                uuid:arr[1]
              }
              this.$set(this.bimListData, 0,obj);   
            }
          }
        })
      } else {
        this.highLightList = '';
        this.bimListData = [];
        this.form.id = undefined
        this.form.projectId = undefined
        this.form.areaId = undefined
        this.form.itemTypeId = undefined
        this.form.planTime = []
        this.form.parameter = undefined
        this.form.dangerSource = undefined
        this.form.levelTypeId = undefined
        this.form.dangerousTypeId = undefined
        this.form.dutyUserTemp = []
        this.form.controlContent = undefined
        // this.form = { projectId: '', dutyUserTemp: [] }
        this.$refs.BForm.clearValidate()
        setTimeout(() => {
          this.$refs.BForm.clearValidate()
        }, 300)
      }
    },
  },
  methods: {
    onSelectTree(){
      this.bimListData= [];
      this.highLightList ='';
    },
    async getData() {
      this.loading = true
      if (!this.initData.projectId) return
      let res = await Api.subPackArea({}, { id: this.initData.projectId, sources: 0 })
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        this.treeData = res.data
      }
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    async handleOk() {
      this.$refs.BForm.validate(async (valid) => {
        if (valid) {
          // if(!this.bimListData.length){
          //   this.$message.warning('请关联bim模型');
          //   return
          //   ;
          // }
          let temp = this.$clone(this.form)
          if(this.bimListData[0]){  //关联bim才传参
              temp.bimId = `${this.bimListData[0].name}&&&&${this.bimListData[0].uuid}`;
              temp.bimModelId = this.modelList[0].modelId;
              temp.modelId = this.modelList[0].id;
              temp.modelFileId = this.modelList[0].modelId;
              temp.modelFileVersion = this.modelList[0].version;
              temp.modelTitle = this.modelList[0].modelTitle;
              }else{
               let delArr = ['bimId','bimModelId','modelId','modelFileId','modelFileVersion','modelTitle'];
               delArr.forEach((item)=> delete temp[item]);
              }
          temp.planTimeEnd = temp.planTime[1]
          temp.planTime = temp.planTime[0]
          temp.dutyUser = {}
          temp.dutyUserTemp.map(v => {
            temp.dutyUser[v.key] = v.label
          })
          let res
          this.loading = true
          if (temp.id) {
            res = await Api.editByDetail(temp)
          } else {
            res = await Api.createByDetail(temp)
          }
          this.loading = false
          if (res.code === this.SUCCESS_CODE) {
            this.$message.success('成功')
            this.$emit('ok')
            this.cancel()
          }
        }
      })

    },
        /**
     * @description: 打开模型
     * @param {Array} data：模型列表或者模型选中项
     */
     relevanceBim(flag=false) {
      if(!this.form.areaId){
        this.$message.warning('请先选择区域');
        return
      }
      if(!this.form.projectId){
        this.$message.warning('请先选择所属单位');
        return
      }
      this.getBimList(flag);
    },
    /**
     * @description: 打开模型
     * @param {Array} data：模型列表或者模型选中项
     */
     handleOpen(data) {
      this.modelList = data
      console.log( this.modelList,22333)
      this.visibleBim = false
      this.visibleRelease = true
    },
    //获取bim 数据
    getBimList(visibleRelease=false){
      let args = {
        pageNum:1,
        pageSize:10,
        param:{
          projectId:this.form.projectId,
          subAreaId:this.form.areaId
        }
      }
      this.loadingBtn = visibleRelease;
       getList(args).then((res) => {
        if (res.code === '0') {
          let data = res.data?.list || [];
          if(data.length==1){
            const params = [{ id: data[0].id, modelId: data[0].modelFileId, version: data[0].modelFileVersion, modelTitle: data[0].modelName,subAreaId:data[0].subAreaId}]
            this.modelList = params;
            this.firstBimData = data[0];
            this.visibleRelease = visibleRelease
            this.loadingBtn = false;
          }else if(data.length>1){
            this.visibleBim = visibleRelease
            this.extraParams.subAreaId = this.form.areaId;
            this.loadingBtn = false;
          }
          else{
            this.$message.warning("请将所选区域关联BIM模型”");
            this.loadingBtn = false;
          }
        }
      })
    },
        /**
     * @description: BIM模型关联
     * @param {Array<Number>} floorIdList：关联楼层列表
     */
     handleBim(floorIdList) {
      this.bimListData = floorIdList;
      this.visibleRelease = false;
      this.highLightList =floorIdList[0].uuid
    },
    delBim(index){
      this.modelList = [];
      this.bimListData.splice(index,1);
      this.highLightList ='';
    }
  }
}
</script>

<style lang="less" scoped>
form .ant-mentions,
form textarea.ant-input {
  height: auto !important;
  width: 100%;
}
.bim-btn{
 display:flex;
 .label{
   width: 135px;
   text-align: right;
   color: rgba(0, 0, 0, 0.85);
 }
 .data-val{
  position: relative;
  padding: 5px 20px;
  .anticon{
    cursor: pointer;
    position:absolute;
    right: 0;
    top: 2px;
  }
  background-color: rgba(235,242,254);
   img{
    width: 20px;
   }
 }
}
</style>